package com.dy.yunying.biz.datasource;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
/**
 * @ClassName DataLayerDorisDataSourceConfig
 * @Description todo
 * @Author nieml
 * @Time 2022/12/29 15:01
 * @Version 1.0
 **/
@Configuration
@MapperScan(basePackages = "com.dy.yunying.biz.dao.doris",sqlSessionFactoryRef = "dorisSqlSessionFactory")
public class DataLayerDorisDataSourceConfig {

	@Autowired
	private MybatisPlusInterceptor mybatisPlusInterceptor;

	@Bean(name = "dataLayerDorisTemplate")
	public JdbcTemplate dorisJdbcTemplate(@Qualifier("dataLayerDorisDataSource") DataSource dataSource) {
		return new JdbcTemplate(dataSource);
	}

	@Bean(name = "dataLayerDorisDataSource")
	@ConfigurationProperties(prefix ="spring.datasource.dorisdatalayer")
	public DataSource dorisDataSource() {
		return DruidDataSourceBuilder.create().build();
	}

	@Bean(name = "dorisSqlSessionFactory")
	// 表示这个数据源是默认数据源
	// @Qualifier表示查找对象
	public MybatisSqlSessionFactoryBean cstSqlSessionFactory(@Qualifier("dataLayerDorisDataSource") DataSource datasource) throws Exception {
		MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
		sqlSessionFactoryBean.setDataSource(dorisDataSource());
		//这里如果用mybatis plus的话，要用mybatis-plus的configuration
		MybatisConfiguration configuration = new MybatisConfiguration();
		//configuration.setMapUnderscoreToCamelCase(false);
		sqlSessionFactoryBean.setConfiguration(configuration);
		sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:/mapper/doris/**/*.xml"));

		//设置 MyBatis-Plus 分页插件
		Interceptor[] plugins = {mybatisPlusInterceptor};
		sqlSessionFactoryBean.setPlugins(plugins);
		return sqlSessionFactoryBean;
	}

	@Bean("dorisSqlSessionTemplate")
	public SqlSessionTemplate test1sqlsessiontemplate(
			@Qualifier("dorisSqlSessionFactory") SqlSessionFactory sessionfactory) {
		return new SqlSessionTemplate(sessionfactory);
	}

}
